package com.rogers.rmcdouga.skirmishgadget.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.gen2.logging.shared.Log;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
import com.google.gwt.widgetideas.graphics.client.ImageLoader;
import com.rogers.rmcdouga.skirmishgadget.client.java.awt.Dimension;
import com.rogers.rmcdouga.skirmishgadget.client.java.awt.Point;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SkirmishGadget implements EntryPoint
{
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

	private BattleMap map;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad()
	{
		final Button sendButton = new Button("Send");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User");

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event)
			{
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler
		{
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event)
			{
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event)
			{
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER)
				{
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendNameToServer()
			{
				sendButton.setEnabled(false);
				String textToServer = nameField.getText();
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer, new AsyncCallback<String>() {
					public void onFailure(Throwable caught)
					{
						// Show the RPC error message to the user
						dialogBox.setText("Remote Procedure Call - Failure");
						serverResponseLabel.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}

					public void onSuccess(String result)
					{
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel.removeStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(result);
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
		
//		final GWTCanvas canvas = new GWTCanvas(400,400);
		    
		final String[] urls = new String[] {"BrightstoneKeep.jpg" /*, "darkcrypt.jpg" */};

//		Log.info("Before ImageLoader");
//		ImageLoader.loadImages(urls,
//				new ImageLoader.CallBack() 
//				{
//					public void onImagesLoaded(ImageElement[] imageHandles)
//					{
//					Log.info("Inside ImageLoader");
//					ImageElement img = imageHandles[0];
//		        
//					//canvas.translate(40, 40);
//					//canvas.scale(0.5f, 0.5f);
//					canvas.drawImage(img, 0, 0);
////					image.setUrl(urls[1]);
//					canvas.stroke();
//					}
//		      
//				});
//
//		Log.info("After ImageLoader");		   

//		final Image image = new Image();
//		image.addLoadHandler(new LoadHandler()
//			{
//				public void onLoad(LoadEvent event) {
//					Log.info("Inside Image Load event handler");
//					// TODO Auto-generated method stub
//					canvas.drawImage(ImageElement.as(image.getElement()), 0, 0);
//				}
//				
//			}
//			);
//
//		DeferredCommand.addCommand(new Command(){
//			public void execute() {
//				Log.info("Setting the image URL");
//				image.setUrl(urls[0]);
//				RootPanel.get("invisibleImageContainer").add(image);
//			}
//		});
//		image.setUrl(urls[0]);
//		RootPanel.get("imageContainer").add(image);

//		canvas.setTitle("Canvas");
//		canvas.arc(200, 200, 100, 0, 360, false);
//		canvas.stroke();
//		canvas.strokeRect(50, 50, 300, 300);
		
		map = new BattleMap(urls[0], 800, 600);
		map.setFiveFootSquare(new Dimension(8,8));
	    VerticalPanel vPanel = new VerticalPanel();
	    vPanel.setWidth("100%");
	    vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		vPanel.add(map);
	    RootPanel.get().add(vPanel);
		Token.CreateToken(new Point(100, 100), "Bodak.png", map);
		Token.CreateToken(new Point(300, 300), "HillGiant.png", map);
		Log.info("After 2D Lines");
	}
}
